<?php

namespace App\Models;

use App\MongoModel as Model;
use App\MongoModel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;

/**
 * Class Group
 * @package App\Models
 * @property string parent_id parent node id
 * @property string name group name
 * @property array children id list of children
 * @property string com_key which company
 */
class Group extends Model
{
    const InputFiled = [
        'name' => '',
        'parent_id'=>'',
        'company_id' =>''
    ];
    protected $fillable = ['name'];
    public $timestamps = false;


    /**
     * 类似无限极分类功能
     * 获取当前分支(pid)下的所有数据
     * @param $data
     * @param $pid
     * @return array
     */
    public function getTree($data, $pid){
        static $arr = array();
        foreach ($data as $v) {
            if($v['parent_id'] == $pid){
                $arr[] = $v;
                $this->getTree($data, $v['id']);
            }
        }
        return $arr;
    }

    /**
     * @param int $_parent_id
     * @return array
     */
    public function genTreeBy($_parent_id = 0) {
        if ($_parent_id === 0) {
            $children = $this->children;
            $result = $this->toArray();
        } else {
            $modelCol = self::find($_parent_id);
            if (is_null($modelCol)) {
                $children = [];
                $result = [];
                if (config('app.debug'))
                    return [$_parent_id => null];
            } else {
                $children = $modelCol->children;
                $result = $modelCol->toArray();
            }
        }

        if (count($children) > 0) {
            $result['children'] = array_map(function($_gid){
                return $this->genTreeBy($_gid);
            }, $children);
        }
        return $result;
    }

    public function getLeafBy($_gid = 0) {
        $current = $_gid === 0 ? $this : self::find($_gid);
        if (is_null($current)) {
            return null;
        }
        $result = [];
        if (count($current->children) === 0) {
            return $current;
        } else {
            $result = array_flatten(array_map(function($_childId) {
                return $this->getLeafBy($_childId);
            }, $current->children));
        }
        return $result;
    }

    /**
     * 根据id,判断是否有子节点
     * @param $id
     * @return bool
     */
    public function hasChildren(){
        return isset($this->children) && !empty($this->children);
    }

    public static function format_group($_data, $_children_ids = null)
    {
        if (empty($_data)) return [];
        $needed = [];
        // 默认传入的children是null,代表获取的是ROOT
        if (is_null($_children_ids)) {
            $judge_field = 'parent_id';
            $judge_values = [0, '', null];
        } else {
            $judge_field = 'id';
            $judge_values = $_children_ids;
        }
        // 截取下次递归需要的数据
        $next_data = array_filter(
            $_data,
            function ($group) use ($judge_field, $judge_values, &$needed) {
                if (isset($group[$judge_field]) && in_array($group[$judge_field], $judge_values)) {
                    array_push($needed, $group);
                    return false;
                }
                return true;
            }
        );
        // 对数据进行递归归组
        return array_map(function ($item) use ($next_data) {
            if (!empty($item['children'])) {
                $item['children'] = self::format_group($next_data, $item['children']);
            }
            return $item;
        }, $needed);
    }

    /**
     * 获取根节点
     * @param $_leaf_id
     * @return array
     */
    public function getRootBy($_leaf_id)
    {
        $result = [];
        while ($_leaf_id) {
            $root = self::find($_leaf_id);
            array_push($result, $root);
            $_leaf_id = $root->parent_id;
        }
        return $result;
    }

    public static function companyTree($company_id) {
        /**@var \App\Models\Group $rootByCompany**/
        $rootByCompany = self::where([
            'company_id' => $company_id,
            [self::equalEmpty('parent_id')],
        ])->first();// 获取该公司下的所有数据且parent_id为0是在管理后台创建渠道的时候生成
        assert(!is_null($rootByCompany), "找不到id为: 【{$company_id}】渠道的根Group,");
        return $rootByCompany->genTreeBy();//获取所有子数据
    }

    public function project() {
        return $this->hasOne(Project::class);
    }

    public function users() {
        return $this->hasMany(User::class);
    }

    public function getParent() {
        return empty($this->parent_id) ? null : static::find($this->parent_id);
    }
}

